package com.alison.shardingalgorithm;

import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @Author alison
 * @Date 2024/12/22 14:00
 * @Version 1.0
 * @Description
 */
public class CustomShardingAlgorithm implements StandardShardingAlgorithm<String> {
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {
        String orderNo = shardingValue.getValue();
        String tableName = "user_" + (orderNo.hashCode() % 2);
        for (String targetName : availableTargetNames) {
            if (targetName.equals(tableName)) {
                return targetName;
            }
        }
        throw new IllegalArgumentException("无法找到合适的分片表");
    }

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<String> shardingValue) {
        Set<String> result = new LinkedHashSet<>();
        // 这里简单处理，如果是范围分片，可以根据范围逻辑确定要命中的表名添加到result集合中
        // 示例中暂未详细实现复杂的范围分片逻辑，只是返回空集合，实际可按需完善
        return result;
    }

    @Override
    public void init() {
        // 初始化方法，可按需添加初始化逻辑，这里暂时为空实现
    }

    @Override
    public String getType() {
        return "custom_sharding_algorithm";
    }
}